import { type App, unref } from 'vue';

export function getPopupContainer (node?: HTMLElement): HTMLElement {
  
  return (node?.parentNode as HTMLElement) ?? document.body;
}

/**
 * @description 将对象作为参数添加到URL
 * @param baseUrl 要被添加的 url 字符串
 * @param obj 添加到 URL 后面的对象参数
 * @returns {string}
 * @example
 let obj = {a: '3', b: '4'}
 setObjToUrlParams('www.baidu.com', obj)
 ==>www.baidu.com?a=3&b=4
 */
export function setObjToUrlParams (baseUrl: string, obj: any): string {
  let parameters = '';
  for (const key in obj) {
    parameters += key + '=' + encodeURIComponent(obj[key]) + '&';
  }
  parameters = parameters.replace(/&$/, '');
  return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, '?') + parameters;
}

export function openWindow (url: string,
  opt?: {target?: TargetContext | string; noopener?: boolean; noreferrer?: boolean}) {
  const { target = '__blank', noopener = true, noreferrer = true } = opt || {};
  const feature: string[] = [];
  
  noopener && feature.push('noopener=yes');
  noreferrer && feature.push('noreferrer=yes');
  
  window.open(url, target, feature.join(','));
}

export function getDynamicProps<T, U> (props: T): Partial<U> {
  const ret: Recordable = {};
  // @ts-ignore
  Object.keys(props).map((key) => {
    ret[key] = unref((props as Recordable)[key]);
  });
  
  return ret as Partial<U>;
}

export const withInstall = (component, alias?: string) => {
  
  const comp = component as any;
  comp.install = (app: App) => {
    
    app.component(comp.name || comp.displayName, component);
    if (alias) {
      app.config.globalProperties[alias] = component;
    }
  };
  return component;
};

export const createStoragePrefixName = (pkgJson) => {
  const { name, version } = pkgJson;
  return `${name}_${version}_`.toUpperCase();
};

export const copyToClipBoard = (content: string, callback?: () => any) => {
  if (!document.queryCommandSupported('copy')) {
    
    callback?.();
  }
  const textarea: HTMLTextAreaElement = document.createElement('textarea');
  textarea.value = content;
  textarea.readOnly = true;
  document.body.appendChild(textarea);
  textarea.select();
  textarea.setSelectionRange(0, content.length);
  const result = document.execCommand('copy');
  if (result) {
    callback?.();
  } else {
    callback?.();
  }
  textarea.remove();
};

export function nofn () {}

export const openNewTab = (url: string, target = '_blank') => {
  const link = document.createElement('a');
  link.href = url;
  link.target = target;
  link.rel = 'noopener';
  link.click();
  link.remove();
};

/** 判断是否为 pwa 应用 */
export function isPwa() {
  return ['fullscreen', 'standalone', 'minimal-ui'].some(
    (displayMode) => window.matchMedia('(display-mode: ' + displayMode + ')').matches
  );
}
